﻿<template>
    <div>

  
  <div class="login-container">
    <div class="login-background"></div>
    <el-row justify="center" align="middle" style="height:100vh;">
      <el-col :span="8" :xs="20" :sm="12" :md="8">
        <el-card class="login-card" shadow="always">
          <div class="login-header">
            <div class="logo">
              <el-icon size="48"><Reading /></el-icon>
            </div>
            <h2>智慧家教管理系统</h2>
            <p>专业的家教服务管理平台</p>
          </div>
              <!-- 切换按钮始终可见 -->
              <div style="text-align:center;margin-bottom:18px;">
                <el-button
                  type="primary"
                  plain
                  style="font-weight:bold;font-size:16px;"
                  @click="switchLoginType"
                >
                  {{ loginType === 'password' ? '使用手机号验证码登录/注册' : '使用用户名密码登录' }}
                </el-button>
              </div>
              <!-- 用户名密码登录 -->
              <el-form
                v-if="loginType === 'password'"
                :model="form"
                @submit.prevent="login"
                :rules="rules"
                ref="loginForm"
              >
            <el-form-item prop="username">
              <el-input 
                v-model="form.username" 
                placeholder="请输入用户名" 
                size="large"
                prefix-icon="User"
              />
            </el-form-item>
            <el-form-item prop="password">
              <el-input 
                v-model="form.password" 
                type="password" 
                placeholder="请输入密码" 
                size="large"
                prefix-icon="Lock"
                show-password
              />
            </el-form-item>
            <el-form-item>
              <el-button 
                type="primary" 
                @click="login" 
                :loading="loading"
                size="large"
                style="width:100%;"
              >
                {{ loading ? '登录中...' : '登录系统' }}
              </el-button>
            </el-form-item>
          </el-form>
              <!-- 手机号验证码登录 -->
              <el-form
                v-else
                :model="phoneForm"
                :rules="phoneRules"
                ref="phoneLoginForm"
                @submit.prevent="phoneLogin"
              >
                <el-form-item prop="phone">
                  <el-input
                    v-model="phoneForm.phone"
                    placeholder="请输入手机号"
                    size="large"
                    prefix-icon="User"
                  />
                </el-form-item>
                <el-form-item prop="code">
                  <el-row :gutter="10" style="width:100%">
                    <el-col :span="16">
                      <el-input
                        v-model="phoneForm.code"
                        placeholder="请输入验证码"
                        size="large"
                        prefix-icon="Lock"
                      />
                    </el-col>
                    <el-col :span="8">
                      <el-button
                        :disabled="codeCountdown > 0 || codeLoading"
                        @click="sendCode"
                        size="large"
                        style="width:100%"
                      >
                        {{ codeCountdown > 0 ? codeCountdown + 's后重发' : '获取验证码' }}
                      </el-button>
                    </el-col>
                  </el-row>
                </el-form-item>
                <el-form-item>
                  <el-button
                    type="primary"
                    @click="phoneLogin"
                    :loading="loading"
                    size="large"
                    style="width:100%;"
                  >
                    {{ loading ? '登录中...' : '验证码登录/注册' }}
                  </el-button>
                </el-form-item>
              </el-form>
          <div v-if="error" class="error-message">
            <el-icon><WarningFilled /></el-icon>
            {{ error }}
          </div>
          <div class="login-footer">
                <p style="display: flex; align-items: center; justify-content: center; gap: 10px; margin: 0;">
                  还没有账号？
                  <el-button link @click="showRegister">立即注册</el-button>
                  <el-button
                    v-if="loginType === 'password'"
                    link
                    @click="switchLoginType"
                  >验证码登录</el-button>
                  <el-button
                    v-else
                    link
                    @click="switchLoginType"
                  >用户名密码登录</el-button>
                </p>
          </div>
        </el-card>
      </el-col>
    </el-row>
        <!-- 注册对话框等保留原有 -->
    <el-dialog v-model="registerVisible" title="用户注册" width="400px">
      <el-form :model="registerForm" :rules="registerRules" ref="registerFormRef">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="registerForm.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="registerForm.password" type="password" placeholder="请输入密码" show-password />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input v-model="registerForm.confirmPassword" type="password" placeholder="请确认密码" show-password />
        </el-form-item>
        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="registerForm.nickname" placeholder="请输入昵称" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="registerVisible = false">取消</el-button>
        <el-button type="primary" @click="register" :loading="registerLoading">注册</el-button>
      </template>
    </el-dialog>
      </div>
  </div>
</template>

<script setup>
  import { ref, onUnmounted } from 'vue'
import request from '../utils/request.js'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Reading, User, Lock, WarningFilled } from '@element-plus/icons-vue'

const form = ref({ username: '', password: '' })
const error = ref('')
const loading = ref(false)
const router = useRouter()
const loginForm = ref()

// 注册相关
const registerVisible = ref(false)
const registerForm = ref({ username: '', password: '', confirmPassword: '', nickname: '' })
const registerLoading = ref(false)
const registerFormRef = ref()

// 表单验证规则
const rules = {
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
}

const registerRules = {
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    { 
      validator: (rule, value, callback) => {
        if (value !== registerForm.value.password) {
          callback(new Error('两次输入密码不一致'))
        } else {
          callback()
        }
      }, 
      trigger: 'blur' 
    }
  ],
  nickname: [{ required: true, message: '请输入昵称', trigger: 'blur' }]
}

  const loginType = ref('phone') // 'password' or 'phone' - 默认显示验证码登录
  
  // 调试信息
  console.log('Login component loaded, loginType:', loginType.value)

  const phoneForm = ref({ phone: '', code: '' })
  const phoneRules = {
    phone: [
      { required: true, message: '请输入手机号', trigger: 'blur' },
      { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }
    ],
    code: [{ required: true, message: '请输入验证码', trigger: 'blur' }]
  }
  const phoneLoginForm = ref()
  const codeLoading = ref(false)
  const codeCountdown = ref(0)
  let codeTimer = null

const login = async () => {
  if (!loginForm.value) return
  
  try {
    const valid = await loginForm.value.validate()
    if (!valid) return
  } catch {
    return
  }
  
  loading.value = true
  error.value = ''
  
  try {
    const res = await request.post('/login', form.value)
    if (res.code === 200) {
      localStorage.setItem('token', res.data.token)
      localStorage.setItem('user', JSON.stringify(res.data.user))
      // 清理可能留下的模拟权限数据，避免产生误判导致 403
      localStorage.removeItem('mockUserRoles')
      localStorage.removeItem('mockRolePermissions')
      localStorage.removeItem('enablePermissionSimulation')
      ElMessage.success('登录成功！')
      router.push('/main')
    } else {
      error.value = res.message || '登录失败'
    }
  } catch (err) {
    error.value = '网络错误，请稍后重试'
    console.error('登录错误:', err)
  } finally {
    loading.value = false
  }
}

const showRegister = () => {
  registerVisible.value = true
  registerForm.value = { username: '', password: '', confirmPassword: '', nickname: '' }
}

const register = async () => {
  if (!registerFormRef.value) return
  
  try {
    const valid = await registerFormRef.value.validate()
    if (!valid) return
  } catch {
    return
  }
  
  registerLoading.value = true
  
  try {
    const { confirmPassword, ...submitData } = registerForm.value
    const res = await request.post('/login/register', submitData)
    if (res.code === 200) {
      ElMessage.success('注册成功！请登录')
      registerVisible.value = false
      form.value.username = registerForm.value.username
    } else {
      ElMessage.error(res.message || '注册失败')
    }
  } catch (err) {
    ElMessage.error('注册失败，请稍后重试')
    console.error('注册错误:', err)
  } finally {
    registerLoading.value = false
  }
}

  const sendCode = async () => {
    if (!phoneForm.value.phone || !/^1[3-9]\d{9}$/.test(phoneForm.value.phone)) {
      ElMessage.warning('请输入正确的手机号')
      return
    }
    codeLoading.value = true
    try {
      // 使用FormData发送表单数据
      const formData = new FormData()
      formData.append('phone', phoneForm.value.phone)
      const res = await request.post('/login/code', formData)
      if (res.code === 200) {
        ElMessage.success('验证码已发送')
        codeCountdown.value = 60
        codeTimer = setInterval(() => {
          codeCountdown.value--
          if (codeCountdown.value <= 0) clearInterval(codeTimer)
        }, 1000)
      } else {
        ElMessage.error(res.message || '验证码发送失败')
      }
    } catch (e) {
      console.error('验证码发送错误:', e)
      ElMessage.error(e.response?.data?.message || e.message || '验证码发送失败')
    }
    codeLoading.value = false
  }

  const phoneLogin = async () => {
    if (!phoneLoginForm.value) return
    try {
      const valid = await phoneLoginForm.value.validate()
      if (!valid) return
    } catch {
      return
    }
    loading.value = true
    error.value = ''
    try {
      // 使用FormData发送表单数据
      const formData = new FormData()
      formData.append('phone', phoneForm.value.phone)
      formData.append('code', phoneForm.value.code)
      const res = await request.post('/login/phone', formData)
      if (res.code === 200) {
        localStorage.setItem('token', res.data.token)
        localStorage.setItem('user', JSON.stringify(res.data.user))
        // 清理可能遗留的模拟权限数据
        localStorage.removeItem('mockUserRoles')
        localStorage.removeItem('mockRolePermissions')
        localStorage.removeItem('enablePermissionSimulation')
        ElMessage.success('登录成功！')
        router.push('/main')
      } else {
        error.value = res.message || '登录失败'
      }
    } catch (err) {
      error.value = '网络错误，请稍后重试'
      console.error('登录错误:', err)
    } finally {
      loading.value = false
    }
  }

  const switchLoginType = () => {
    loginType.value = loginType.value === 'password' ? 'phone' : 'password'
    console.log('Login type switched to:', loginType.value)
    error.value = ''
  }

  onUnmounted(() => {
    if (codeTimer) clearInterval(codeTimer)
  })
</script>

<style scoped>
.login-container {
  position: relative;
  height: 100vh;
  overflow: hidden;
}

.login-background {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  background-size: 400% 400%;
  animation: gradientShift 15s ease infinite;
}

@keyframes gradientShift {
  0% { background-position: 0% 50%; }
  50% { background-position: 100% 50%; }
  100% { background-position: 0% 50%; }
}

.login-card {
  position: relative;
  z-index: 10;
  backdrop-filter: blur(10px);
  background: rgba(255, 255, 255, 0.95);
  border-radius: 20px;
  padding: 20px;
  box-shadow: 0 15px 35px rgba(0, 0, 0, 0.1);
}

.login-header {
  text-align: center;
  margin-bottom: 30px;
}

.logo {
  margin-bottom: 15px;
}

.logo .el-icon {
  color: #667eea;
}

.login-header h2 {
  margin: 10px 0;
  color: #2c3e50;
  font-weight: 600;
}

.login-header p {
  color: #7f8c8d;
  font-size: 14px;
  margin: 0;
}

.error-message {
  color: #e74c3c;
  text-align: center;
  margin-top: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 5px;
}

.login-footer {
  text-align: center;
  margin-top: 20px;
  color: #7f8c8d;
  font-size: 14px;
}

.el-button--text {
  color: #667eea;
  font-weight: 500;
}

.el-button--text:hover {
  color: #5a67d8;
}

:deep(.el-input__wrapper) {
  border-radius: 10px;
}

:deep(.el-button--primary) {
  border-radius: 10px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
}

:deep(.el-button--primary:hover) {
  background: linear-gradient(135deg, #5a67d8 0%, #6b46a3 100%);
}
</style>
